package com.example.rule.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.rule.common.enums.ConditionLogicEnum;
import com.example.rule.engine.AviatorEngine;
import com.example.rule.engine.GroovyEngine;
import com.example.rule.entity.dto.RuleSaveDTO;
import com.example.rule.entity.po.ConditionPO;
import com.example.rule.entity.po.RulePO;
import com.example.rule.mapper.RuleMapper;
import com.example.rule.service.ConditionService;
import com.example.rule.service.RuleService;
import com.example.rule.toolkit.ExpressionBuilder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class RuleServiceImpl extends ServiceImpl<RuleMapper, RulePO> implements RuleService {

    private final RuleMapper ruleMapper;
    private final ConditionService conditionService;
    private final GroovyEngine groovyEngine;
    private final AviatorEngine aviatorEngine;


    @Override
    public void save(RuleSaveDTO params) {
        // 参数非空校验
        if (params == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }

        // 规则名称非空校验
        if (StrUtil.isBlank(params.getName())) {
            throw new IllegalArgumentException("规则名称不能为空");
        }

        // 数据值非空校验
        if (params.getData() == null) {
            throw new IllegalArgumentException("数据值不能为空");
        }

        // 条件数量校验（必须大于等于 0）
        if (params.getConditionNum() == null || params.getConditionNum() < 0) {
            throw new IllegalArgumentException("条件数量必须为非负整数");
        }

        // 逻辑关系描述非空校验
        if (StrUtil.isBlank(params.getLogicDesc())) {
            throw new IllegalArgumentException("逻辑关系描述不能为空");
        }

        // 校验逻辑关系是否合法（调用 ConditionLogicEnum 获取 symbol）
        try {
            ConditionLogicEnum.getOperatorByDescription(params.getLogicDesc());
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("不支持的逻辑关系: " + params.getLogicDesc());
        }

        // 查询随机条件列表
        Integer conditionNum = params.getConditionNum();
        List<ConditionPO> list = conditionService.list(conditionNum);

        // 如果查询到的条件数量小于所需数量，抛出异常或做默认处理
        if (list.size() < conditionNum) {
            throw new IllegalArgumentException("数据库中可用条件不足，无法构建完整规则");
        }

        // 构建表达式
        String expression = ExpressionBuilder.buildExpression(list, params.getLogicDesc());
        log.info("rule expression: {}", expression);

        // 构建 RulePO 并插入数据库（取消注释后使用）
        RulePO po = RulePO.builder()
                .name(params.getName())
                .data(params.getData())
                .expression(expression)
                .build();

        // 插入数据库
         ruleMapper.insert(po);
    }

    @Override
    public void execute() {
        List<RulePO> list = list();
        long start1 = System.currentTimeMillis();
        double res1 = groovyEngine.execute(list);
        long end1 = System.currentTimeMillis();
        log.info("Groovy执行耗时: {}ms, 结果: {}", end1 - start1, res1);
        long start2 = System.currentTimeMillis();
        double res2 = aviatorEngine.execute(list);
        long end2 = System.currentTimeMillis();
        log.info("Aviator执行耗时: {}ms, 结果: {}", end2 - start2, res2);
    }
}
